﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TFSHelper.cs" company="Scrum for Team System">
//   None
// </copyright>
// <summary>
//   The tfs helper.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace ScrumForTeamSystem.Setup.SfTSDeployment
{
    using System;
    using System.Windows.Forms;

    using Microsoft.TeamFoundation.Client;

    /// <summary>
    /// The tfs helper.
    /// </summary>
    public static class TfsHelper
    {
        /// <summary>
        /// The UI credentials provider instance.
        /// </summary>
        private static readonly UICredentialsProvider provider;

        /// <summary>
        /// Initializes static members of the <see cref="TfsHelper"/> class.
        /// </summary>
        static TfsHelper()
        {
            provider = new UICredentialsProvider();
        }

        /// <summary>
        /// Gets the TFS URL.
        /// </summary>
        /// <returns>A tfs application instance.</returns>
        public static TfsConfigurationServer GetTfsInstance()
        {
            var dialog = new TeamProjectPicker(TeamProjectPickerMode.NoProject, false, provider);

            return dialog.ShowDialog() != DialogResult.OK 
                       ? null 
                       : dialog.SelectedTeamProjectCollection.ConfigurationServer;
        }

        /// <summary>
        /// Gets the TFS instance.
        /// </summary>
        /// <param name="tfsurl">The tfsurl.</param>
        /// <returns>A tfs application instance.</returns>
        public static TfsConfigurationServer GetTfsInstance(string tfsurl)
        {
            TfsConfigurationServer instance;

            try
            {
                instance = TfsConfigurationServerFactory.GetConfigurationServer(new Uri(tfsurl), provider);
                instance.EnsureAuthenticated();
            }
            catch (Exception)
            {
                return GetTfsInstance();
            }

            return instance;
        }
    }
}